let express = require('express');
let router = express.Router();
const Login = require("../../../../controllers/sys_login.controller");

/**
 * @typedef loginBody
 * @property {string} verifyCode.required - 请输入验证码
 * @property {string} userName.required - 请输入账号
 * @property {string} password.required - 请输入密码
 */

/**
 * 账号登录
 * @route POST /api/public/v1/login
 * @group 登录 - login
 * @param {loginBody.model} loginBody.body.required
 * @returns {object} 成功
 * @returns {ResponseMeta.model} 错误异常
 */
router.post("/", function (req, res) {
    const pm = req.body;
    // 请求验证+
    if (!pm.verify_code || !pm.key) return res.sendResult({ data: '', code: -1, message: "验证码不能为空！" });
    if (!pm.user_name) return res.sendResult({ data: '', code: -1, message: "用户名不能为空！" });
    if (!pm.password) return res.sendResult({ data: '', code: -1, message: "密码不能为空！" });
    if (pm.key !== req.session?.captcha_key) return res.sendResult({ data: '', code: -1, message: "验证码不正确或已失效！" });
    // 转小写 验证码
    if (pm.verify_code.toLowerCase() !== req.session?.captcha_text) return res.sendResult({ data: '', code: -1, message: "验证码不正确或已失效！" });
    return Login.login({ pm, req, res })
});

/**
 * @typedef loginPhoneBody
 * @property {string} verifyCode.required - 请输入验证码
 * @property {string} phone.required - 请输入手机号
 */


/**
 * 手机登录
 * @route POST /api/public/v1/login/phone
 * @group 登录 - login
 * @param {loginPhoneBody.model} loginPhoneBody.body.required
 * @returns {object} 成功
 * @returns {ResponseMeta.model} 错误异常
 */
router.post("/phone", function (req, res) {
    const pm = req.body;
    if (!pm.verify_code) return res.sendResult({ data: '', code: -1, message: "验证码不能为空！" });
    if (!pm.phone) return res.sendResult({ data: '', code: -1, message: "手机号不能为空！" });
    return Login.findUser({ phone: pm.phone }, { pm, req, res })
});

/**
 * @typedef loginEmailBody
 * @property {string} verifyCode.required - 请输入验证码
 * @property {string} email.required - 请输入邮箱
 */
/**
 * 邮箱登录
 * @route POST /api/public/v1/login/email
 * @group 登录 - login
 * @param {loginEmailBody.model} loginEmailBody.body.required
 * @returns {object} 成功
 * @returns {ResponseMeta.model} 错误异常
 */
router.post("/email", function (req, res) {
    const pm = req.body;
    if (!pm.verify_code) return res.sendResult({ data: '', code: -1, message: "验证码不能为空！" });
    if (!pm.email) return res.sendResult({ data: '', code: -1, message: "邮箱不能为空！" });
    return Login.findUser({ email: pm.email }, { pm, req, res })
})


/**
 * 刷新token
 * @route POST /api/public/v1/login/token
 * @group 登录 - login
 * @param {object} body.body - 请求参数 会话 Id 必填
 * @returns {object} 成功
 * @returns {ResponseMeta.model} 错误异常
 */
router.post("/token", Login.refreshToken)



module.exports = router;
